package com.example.service;

import com.example.entity.MailRequestVo;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * Author wangJinLong
 * Date 2025/11/19 16:12
 **/
@Slf4j
@Service
public class MailServiceImpl implements MailService {

    @Value("${spring.mail.username}")
    private String username;

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void sendMail(MailRequestVo mailRequestVo) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");

        helper.setFrom(username);
        helper.setTo(mailRequestVo.getTo());
        helper.setSubject(mailRequestVo.getSubject());
        helper.setText(mailRequestVo.getContent(), true);

        // 添加附件
        if (mailRequestVo.getAttachment() != null && mailRequestVo.getAttachment().exists()) {
            // 如果未指定 fileName，则使用原文件名
            String attachName = (mailRequestVo.getFileName() != null) ? mailRequestVo.getFileName() : mailRequestVo.getAttachment().getName();
            helper.addAttachment(attachName, mailRequestVo.getAttachment());
        }
        if (mailRequestVo.getFilepath() != null) {
            try {
                File file = new File(mailRequestVo.getFilepath());
                // 如果未指定 fileName，则使用原文件名
                String attachName = (mailRequestVo.getFileName() != null) ? mailRequestVo.getFileName() : file.getName();
                helper.addAttachment(attachName, file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        javaMailSender.send(mimeMessage);
    }
}
